package com.example.dw.admin.controller;

import com.example.dw.common.Result;
import com.example.dw.common.ResultCode;
import com.example.dw.admin.dto.AdminLoginDTO;
import com.example.dw.admin.dto.AdminUpdateUserDTO;
import com.example.dw.admin.dto.AdminUpdatePasswordDTO;
import com.example.dw.admin.service.AdminAuthService;
import com.example.dw.admin.entity.AdminUser;
import com.example.dw.admin.mapper.AdminUserMapper;
import com.example.dw.utils.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理端认证控制器
 * @author system
 * @since 2024-01-01
 */
// 允许跨域
@CrossOrigin(origins = "*")
@Tag(name = "管理端认证", description = "管理员登录和信息管理接口")
@Slf4j
@RestController
@RequestMapping("/admin")
@Validated
public class AdminAuthController {

    @Autowired
    private AdminAuthService adminAuthService;

    @Autowired
    private AdminUserMapper adminUserMapper;

    /**
     * 管理员登录
     */
    @Operation(summary = "管理员登录", description = "管理员用户名密码登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody @Validated AdminLoginDTO loginDTO) {
        try {
            log.info("管理员登录请求: {}", loginDTO.getUsername());
            
            Map<String, Object> result = adminAuthService.login(loginDTO);
            
            log.info("管理员登录成功: {}", loginDTO.getUsername());
            return Result.success("登录成功", result);
            
        } catch (Exception e) {
            log.error("管理员登录失败: {}, 错误: {}", loginDTO.getUsername(), e.getMessage());
            return Result.error(401, e.getMessage());
        }
    }

    /**
     * 创建测试管理员账号
     * 仅用于开发和测试环境，生产环境应关闭此接口
     */
    @Operation(summary = "创建测试管理员", description = "创建默认的测试管理员账号")
    @PostMapping("/init-test-admin")
    public Result<?> initTestAdmin() {
        try {
            // 检查是否已存在管理员
            QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", "admin");
            AdminUser existingAdmin = adminUserMapper.selectOne(queryWrapper);
            
            if (existingAdmin != null) {
                return Result.error("测试管理员已存在，用户名: admin");
            }
            
            // 创建测试管理员
            AdminUser testAdmin = new AdminUser();
            testAdmin.setUsername("admin");
            testAdmin.setPassword(PasswordUtil.encode("admin123")); // 默认密码: admin123
            testAdmin.setNickname("测试管理员");
            testAdmin.setPhone("13888888888");
            testAdmin.setEmail("admin@test.com");
            testAdmin.setSex("1"); // 1-男性
            testAdmin.setCreatedAt(java.time.LocalDateTime.now().toString());
            
            int result = adminUserMapper.insert(testAdmin);
            
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", testAdmin.getId());
                data.put("username", testAdmin.getUsername());
                data.put("nickname", testAdmin.getNickname());
                data.put("defaultPassword", "admin123");
                
                log.info("测试管理员创建成功: {}", testAdmin.getUsername());
                return Result.success("测试管理员创建成功", data);
            } else {
                return Result.error("测试管理员创建失败");
            }
            
        } catch (Exception e) {
            log.error("创建测试管理员失败: {}", e.getMessage());
            return Result.error("创建测试管理员失败: " + e.getMessage());
        }
    }

    /**
     * 重置测试管理员密码
     * 仅用于开发和测试环境
     */
    @Operation(summary = "重置测试管理员密码", description = "重置测试管理员密码为默认值")
    @PostMapping("/reset-test-admin")
    public Result<?> resetTestAdmin() {
        try {
            QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", "admin");
            AdminUser admin = adminUserMapper.selectOne(queryWrapper);
            
            if (admin == null) {
                return Result.error("测试管理员不存在，请先创建");
            }
            
            // 重置密码
            AdminUser updateAdmin = new AdminUser();
            updateAdmin.setId(admin.getId());
            updateAdmin.setPassword(PasswordUtil.encode("admin123"));
            updateAdmin.setUpdatedAt(java.time.LocalDateTime.now());
            
            int result = adminUserMapper.updateById(updateAdmin);
            
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("username", "admin");
                data.put("resetPassword", "admin123");
                
                log.info("测试管理员密码重置成功");
                return Result.success("测试管理员密码重置成功", data);
            } else {
                return Result.error("密码重置失败");
            }
            
        } catch (Exception e) {
            log.error("重置测试管理员密码失败: {}", e.getMessage());
            return Result.error("重置测试管理员密码失败: " + e.getMessage());
        }
    }

    /**
     * 获取管理员信息
     */
    @Operation(summary = "获取管理员信息", description = "获取当前登录管理员的详细信息")
    @GetMapping("/adminuser")
    public Result<?> getAdminInfo(HttpServletRequest request) {
        try {
            Integer adminId = (Integer) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error(401, "未登录或token无效");
            }
            
            AdminUser admin = adminAuthService.getAdminInfo(adminId);
            return Result.success("获取管理员信息成功", admin);
            
        } catch (Exception e) {
            log.error("获取管理员信息失败: {}", e.getMessage());
            return Result.error("获取管理员信息失败");
        }
    }

    /**
     * 修改管理员信息
     */
    @Operation(summary = "修改管理员信息", description = "更新管理员的基本信息")
    @PostMapping("/admin/updateUser")
    public Result<?> updateAdminInfo(@RequestBody @Validated AdminUpdateUserDTO updateDTO, 
                                   HttpServletRequest request) {
        try {
            Integer adminId = (Integer) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error(401, "未登录或token无效");
            }
            
            updateDTO.setUserid(adminId);
            adminAuthService.updateAdminInfo(updateDTO);
            
            return Result.success("管理员信息更新成功");
            
        } catch (Exception e) {
            log.error("修改管理员信息失败: {}", e.getMessage());
            return Result.error("修改管理员信息失败");
        }
    }

    /**
     * 修改管理员密码
     */
    @Operation(summary = "修改管理员密码", description = "修改当前管理员的登录密码")
    @PostMapping("/admin/updateUserPw")
    public Result<?> updateAdminPassword(@RequestBody @Validated AdminUpdatePasswordDTO updatePasswordDTO,
                                       HttpServletRequest request) {
        try {
            Integer adminId = (Integer) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error(401, "未登录或token无效");
            }
            
            updatePasswordDTO.setUserid(adminId);
            adminAuthService.updateAdminPassword(updatePasswordDTO);
            
            return Result.success("密码修改成功");
            
        } catch (Exception e) {
            log.error("修改管理员密码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
} 